using GLib;
using DBus;
using Xml;

namespace Malem {

	protected class JobsManager: GLib.Object {
		private Gee.HashMap<string, JobObject> jobs;
		private Gee.HashMap<string, Gee.ArrayList<JobObject>> jobs_by_dbus_name;
	
		construct {
			jobs = new Gee.HashMap<string, JobObject>(str_hash, str_equal);
			jobs_by_dbus_name = new Gee.HashMap<string, Gee.ArrayList<JobObject>>(str_hash, str_equal);
		}

		public bool addJob(JobObject job) {
			Gee.ArrayList<JobObject> gaj = jobs_by_dbus_name.get(job.dbusName);
			if (gaj==null) gaj = new Gee.ArrayList<JobObject>();
			gaj.add(job);
			this.jobs_by_dbus_name.set(job.dbusName, gaj);
			this.jobs.set(job.dbusName+":"+job.dbusPath, job);

			this.onStarted(job);

			return true;
		}

		public bool removeJob(JobObject job, bool isCompletedWithSuccess) {
			Gee.ArrayList<JobObject> gaj = this.jobs_by_dbus_name.get(job.dbusName);
			if (gaj!=null) {
				gaj.remove(job);
				if (gaj.size==0) this.jobs_by_dbus_name.remove(job.dbusName);
				else this.jobs_by_dbus_name.set(job.dbusName, gaj);
			}
			this.jobs.remove(job.dbusName+":"+job.dbusPath);

			this.onCompleted(job, isCompletedWithSuccess);		
			return true;
		}

		public JobObject? getJob(string dbus_name, string dbus_path) {
			return this.jobs.get(dbus_name+":"+dbus_path);
		}

		public Gee.Collection<JobObject> getJobs() {
			return this.jobs.get_values();
		}

		public Gee.ArrayList<JobObject> getJobsByDBusName(string dbus_name) {
			return this.jobs_by_dbus_name.get(dbus_name);
		}

		public signal void	onStarted(JobObject job);
		public signal void	onCompleted(JobObject job, bool isCompletedWithSuccess);
	}

}

